package Java7_Concurrency_Cookbook.thread_synchronized_helper.cyclic_barrier;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * 搜索者
 * @author lixiangke
 */
public class Searcher implements Runnable {

    private int firstRow;
    private int lastRow;
    private MatrixMock mock;
    private Results results;
    /**
     * 要搜索的数字
     */
    private int number;
    private CyclicBarrier barrier;

    public Searcher(int firstRow, int lastRow, MatrixMock mock, Results results, int number, CyclicBarrier barrier) {
        this.firstRow = firstRow;
        this.lastRow = lastRow;
        this.mock = mock;
        this.results = results;
        this.number = number;
        this.barrier = barrier;
    }

    @Override
    public void run() {
        int counter;
        String tName = Thread.currentThread().getName();
        System.out.println(tName + " : Processing lines from " + firstRow + " to " + lastRow);
        for (int i = firstRow; i < lastRow; i++) {
            //System.out.println("==============" + i);
            int[] row = mock.getRow(i);
            counter = 0;
            for (int j = 0; j < row.length; j++) {
                if (row[j] == number) {
                    counter++;
                }
            }
            results.setData(i, counter);
        }
        System.out.println(tName + " : Lines processed.");

        try {
            barrier.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        }
    }
}
